package sit.engreal.leetcode.problems100;

import org.junit.jupiter.api.Assertions;

/**
 * <a herf="https://leetcode.cn/problems/string-to-integer-atoi/">8. 字符串转换整数 (atoi)</a>
 */
public class LeetCode8 {
    public static class Solution {
        public int myAtoi(String s) {
            int n = 0;
            int i = 0;
            for (; i < s.length(); i++) {
                if (!Character.isWhitespace(s.charAt(i))) {
                    break;
                }
            }
            if (i >= s.length()) {
                return 0;
            }

            int sign = 1;
            if (s.charAt(i) == '-') {
                sign = -1;
                i++;
            } else if (s.charAt(i) == '+') {
                i++;
            }

            for (; i < s.length() && Character.isDigit(s.charAt(i)); i++) {
                if (n > (Integer.MAX_VALUE / 10) || n < (Integer.MIN_VALUE / 10)) {
                    return sign == 1 ? Integer.MAX_VALUE : Integer.MIN_VALUE;
                }
                int v = s.charAt(i) - '0';
                if (n == Integer.MAX_VALUE / 10) {
                    if (v >= Integer.MAX_VALUE % 10) {
                        return Integer.MAX_VALUE;
                    }
                }
                if (n == Integer.MIN_VALUE / 10) {
                    if (v >= Math.abs(Integer.MIN_VALUE % 10)) {
                        return Integer.MIN_VALUE;
                    }
                }

                n *= 10;
                n += (sign * v);
            }
            return n;
        }
    }

    public static void main(String[] args) {
        final Solution solution = new Solution();

        Assertions.assertEquals(0, solution.myAtoi("   "));
        Assertions.assertEquals(4193, solution.myAtoi("4193 with words"));
        Assertions.assertEquals(2147483646, solution.myAtoi("2147483646"));
        Assertions.assertEquals(Integer.MAX_VALUE, solution.myAtoi("2147483647"));
        Assertions.assertEquals(Integer.MAX_VALUE, solution.myAtoi("2147483648"));
        Assertions.assertEquals(-2147483647, solution.myAtoi("-2147483647"));
        Assertions.assertEquals(Integer.MIN_VALUE, solution.myAtoi("-2147483648"));
        Assertions.assertEquals(Integer.MIN_VALUE, solution.myAtoi("-2147483649"));
    }
}
